<?php


namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Exception;

class Sales extends Backend
{
    public function index()
    {
        // 查询出登录的是哪个角色
        $group_id = $this->auth->getGroups()[0]['group_id'];
        //如果是admin要做特殊处理
        if($group_id == 1){
            return  $this->view->fetch('Architect/index');
        }
        $userinfo =$this->getUserInfo($this->auth->id,$group_id);
        $userinfo['phone'] = substr_replace($userinfo['phone'],'****',3,4);
        // 分销记录
        $firstCenter = Db::name('invest')->where(['uid'=> $userinfo['id'],'role'=>$this->getTable($group_id)])->select();
        $firstData = $this->getDownUser($this->getTable($group_id),$userinfo['id']);
        $scondData = [];
        if(!empty($firstCenter)){
                foreach ($firstCenter as $v){
                    $res = $this->getDownUser($v['to_role'],$v['to_uid']);
                  $scondData =   array_merge($scondData,$res);
                }
        }
        //todo 佣金记录  $firstCenter 一级成员
        $secondCenter = [];
        foreach ($firstCenter as $k => $v){
            $res = Db::name('invest')->where(['uid'=>$v['uid'],'role'=>$v['role'],'to_role'=>'student'])->select();
            $secondCenter = array_merge($secondCenter,$res);
            if($v['to_role'] != 'student'){
                unset($firstData[$k]);
            }
        }
        $allStudent = array_column(array_merge($firstData,$secondCenter),'to_uid');
        $orders = Db::name('order')->alias('o')
                    ->join('invest_earnings ie','o.id = ie.order_id')
                    ->join('student s','o.userId = s.id')
                    ->where(['userId'=>['in',$allStudent],'ie.type' => '2'])
                    ->field('s.nick_name,ie.earnings,ie.create_time,o.batch_id')
                    ->select();
        $this->assign('order',$orders);
        $this->assign(['firstData' => $firstData,'secondData' => $scondData]);
        $this->assign('userInfo',$userinfo);
        $this->assign("sexList",['man' => __('Sex man'), 'woman' => __('Sex woman')]);
        return $this->view->fetch();
    }

    public function editInfo(){
        $param = $this->request->post("row/a");
        if(empty($param['nick_name'])){
            $this->error('昵称不能为空');
        }
        $table = $this->getTable($this->auth->getGroups()[0]['group_id']);
        Db::startTrans();
        try {
            Db::name('admin')->where('id',$this->auth->id)->update(['nickname'=> $param['nick_name']]);
            Db::name($table)->where('admin_id',$this->auth->id)->update(['nick_name'=> $param['nick_name'],'sex'=>$param['sex']]);
            Db::commit();
            $this->success();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    private function getDownUser($role,$uid){
        $forData = ['teacher','helper','student'];
        $data  = [];
        foreach ($forData as $v){
            $user = Db::name('invest')->alias('i')
                ->join($v . ' t','i.to_uid = t.id','LEFT')
                ->where(['uid' => $uid,'role' => $role,'to_role'=>$v])
                ->field('phone,to_role,nick_name,register_time,phone,sale_person,sale_money')
                ->select();
            if(!empty($user)){
                foreach ($user as &$vs){
                    $vs['phone'] = substr_replace($vs['phone'],'****',3,4);
                    $vs['roles'] = $this->getRoles($vs['to_role']);
                }
            }
            $data = array_merge($data,$user);
        }
        return $data;
    }

    private function getRoles($role){
        $roles = '';
        switch ($role){
            case 'teacher': $roles = '教师';break;
            case 'student': $roles = '学生';break;
            case 'helper': $roles = '助教';break;
            case 'partner': $roles = '合伙人';break;
        }
        return $roles;
    }
    private function getUserInfo($id,$groupID){
        if($groupID == 1){
            return $this->auth->getUserInfo();
        }
        $table = $this->getTable($groupID);
        return Db::name($table)->where('admin_id',$id)->find();
    }
    private function  getTable($groupID){
        $table = '';
        switch ($groupID){
            case '2': $table = 'teacher'; break;
            case '4': $table = 'helper'; break;
            case '6': $table = 'partner'; break;
        }
        return $table;
    }
}